package com.xxwy.webSocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.Instant;

/**
 * @author wy
 * @date 2020/3/6 14:17
 *
 * TextWebSocketFrame表示一种文本帧（frame）
 */
public class MyWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
    System.out.println("服务器收到消息: " + msg.text());

    //回复
    ctx.writeAndFlush(new TextWebSocketFrame("你说的都对!!!\n" + Instant.now()));
  }

  @Override
  public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

    //asLongText 唯一
    //asShortText 不唯一
    System.out.println("有一个人来了：" + ctx.channel().id().asLongText());

  }

  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    System.out.println("有一个人走了：" + ctx.channel().id().asLongText());
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
  }
}
